<template>
  <div class="card content-box">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="160px">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item :label="t('common.field.config')" prop="config_id" v-if="config_id < 1 && ruleForm.id < 1">
            <SelectV3 v-model="ruleForm.config_id" :url="groupList" />
          </el-form-item>

          <el-form-item :label="t('common.field.label')" prop="label">
            <el-input v-model="ruleForm.label" />
          </el-form-item>

          <el-form-item :label="t('common.field.field')" prop="field">
            <el-input v-model="ruleForm.field" />
          </el-form-item>

          <el-form-item :label="t('common.field.value')" prop="value">
            <el-input v-model="ruleForm.value" />
          </el-form-item>

          <el-form-item :label="t('common.field.input')" prop="input">
            <el-radio-group v-model="ruleForm.input">
              <el-radio v-for="label in inputItems" :label="label" :key="label" border />
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="t('common.field.is_unique')" prop="is_unique">
            <el-radio-group v-model="ruleForm.is_unique">
              <el-radio :label="1" border>{{ $t("common.yes") }}</el-radio>
              <el-radio :label="0" border>{{ $t("common.no") }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item :label="t('common.status')" prop="status">
            <el-radio-group v-model="ruleForm.status">
              <el-radio :label="10" border>{{ $t("common.normal") }}</el-radio>
              <el-radio :label="20" border>{{ $t("common.disable") }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="14">
          <el-form-item prop="rules">
            <template #label> {{ $t("common.field.rules") }} &nbsp;<el-button @click="addRules">+</el-button> </template>
            <el-col :span="24">
              <el-card shadow="hover" v-for="(rule, index) in ruleForm.rules" :key="index">
                <el-row>
                  <template v-for="(item, kIndex) in rule" :key="kIndex">
                    <div class="el-col el-col-9" v-if="kIndex != 'message'">
                      <div class="el-input el-input--default el-input-group el-input-group--prepend">
                        <!-- input --><!-- prepend slot -->
                        <div class="el-input-group__prepend">{{ kIndex }}</div>
                        <div class="el-input__wrapper">
                          <input
                            class="el-input__inner"
                            type="text"
                            autocomplete="off"
                            tabindex="0"
                            readonly
                            :value="ruleForm.rules[index][kIndex]"
                          />
                        </div>
                      </div>
                    </div>
                  </template>
                  <el-col :span="1"></el-col>
                  <el-col :span="9">
                    <el-input v-model="ruleForm.rules[index]['message']" readonly>
                      <template #prepend>{{ $t("common.message") }}</template>
                    </el-input>
                  </el-col>
                  <el-col :span="1"></el-col>
                  <el-col :span="1">
                    <el-button :icon="Delete" @click="delRules(index)" />
                  </el-col>
                </el-row>
              </el-card>
            </el-col>
          </el-form-item>

          <el-form-item :label="t('common.field.source')" prop="source">
            <template #label> {{ $t("common.field.source") }} &nbsp;<el-button @click="addSource">+</el-button> </template>

            <el-col :span="24">
              <el-card shadow="hover" v-for="(source, index) in ruleForm.source" :key="index">
                <el-row>
                  <template v-for="(item, kIndex) in source" :key="kIndex">
                    <div class="el-col el-col-9">
                      <div class="el-input el-input--default el-input-group el-input-group--prepend">
                        <!-- input --><!-- prepend slot -->
                        <div class="el-input-group__prepend">{{ kIndex }}</div>
                        <div class="el-input__wrapper">
                          <input
                            class="el-input__inner"
                            type="text"
                            autocomplete="off"
                            tabindex="0"
                            readonly
                            :value="ruleForm.source[index][kIndex]"
                          />
                        </div>
                      </div>
                    </div>
                    <el-col :span="1"></el-col>
                  </template>

                  <el-col :span="1">
                    <el-button :icon="Delete" @click="delSource(index)" />
                  </el-col>
                </el-row>
              </el-card>
            </el-col>
          </el-form-item>

          <el-form-item :label="t('common.field.props')" prop="props">
            <template #label> {{ $t("common.field.props") }} &nbsp;<el-button @click="addProps">+</el-button> </template>

            <el-card shadow="hover" v-for="(props, index) in ruleForm.props" :key="index">
              <el-row :gutter="20">
                <el-col :span="18" v-for="(prop, kIndex) in props" :key="kIndex">
                  <div class="el-input el-input--default el-input-group el-input-group--prepend">
                    <div class="el-input-group__prepend">{{ kIndex }}</div>
                    <div class="el-input__wrapper">
                      <input
                        class="el-input__inner"
                        type="text"
                        autocomplete="off"
                        tabindex="0"
                        readonly
                        :value="ruleForm.props[index][kIndex]"
                      />
                    </div>
                  </div>
                </el-col>
                <el-col :span="3">
                  <el-button :icon="Delete" @click="delProps(index)" />
                </el-col>
              </el-row>
            </el-card>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="t('common.field.desc')" prop="desc">
            <el-input type="textarea" v-model="ruleForm.desc" maxlength="255" :autosize="{ minRows: 4, maxRows: 8 }" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8"></el-col>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-row>
    </el-form>

    <el-dialog v-model="addRuleDrawer" :title="t('common.field.ruleTitle')" width="40%" align-center :show-close="false">
      <el-form ref="addRuleFormRef" :model="ruleItem" :rules="addRule">
        <el-form-item :label="t('common.field.ruleItem')" prop="rule">
          <el-input v-model="ruleItem.rule" />
        </el-form-item>

        <el-form-item :label="t('common.field.ruleValue')" prop="value">
          <el-input v-model="ruleItem.value" />
        </el-form-item>

        <el-form-item :label="t('common.field.message')" prop="message">
          <el-input v-model="ruleItem.message" />
        </el-form-item>

        <span class="dialog-footer">
          <el-button @click="closeRuleItem(addRuleFormRef)" type="danger">{{ t("common.cancel") }}</el-button>
          <el-button @click="addRuleItem(addRuleFormRef)" type="success">{{ t("common.add") }}</el-button>
        </span>
      </el-form>
    </el-dialog>

    <el-dialog v-model="addSourceDrawer" :title="t('common.field.ruleTitle')" width="40%" align-center :show-close="false">
      <el-form ref="addSourceFormRef" :model="sourceItem" :rules="sourceRule">
        <el-form-item :label="t('common.field.label')" prop="label">
          <el-input v-model="sourceItem.label" />
        </el-form-item>

        <el-form-item :label="t('common.field.value')" prop="value">
          <el-input v-model="sourceItem.value" />
        </el-form-item>

        <span class="dialog-footer">
          <el-button @click="closeSourceItem(addSourceFormRef)" type="danger">{{ t("common.cancel") }}</el-button>
          <el-button @click="addSourceItem(addSourceFormRef)" type="success">{{ t("common.add") }}</el-button>
        </span>
      </el-form>
    </el-dialog>

    <el-dialog v-model="addPropDrawer" :title="t('common.field.ruleTitle')" width="40%" align-center :show-close="false">
      <el-form ref="addPropFormRef" :model="propItem" :rules="propRule">
        <el-form-item :label="t('common.field.attribute')" prop="label">
          <el-input v-model="propItem.label" />
        </el-form-item>

        <el-form-item :label="t('common.field.value')" prop="value">
          <el-input v-model="propItem.value" />
        </el-form-item>

        <span class="dialog-footer">
          <el-button @click="closePropItem(addPropFormRef)" type="danger">{{ t("common.cancel") }}</el-button>
          <el-button @click="addPropItem(addPropFormRef)" type="success">{{ t("common.add") }}</el-button>
        </span>
      </el-form>
    </el-dialog>
  </div>
</template>
<script setup lang="ts" name="dynamicForm">
import { fieldCreate as Create, fieldUpdate as Update, fieldDetail as getDetail, groupList } from "@/api/modules/common";
import SelectV3 from "@/components/SelectV3/index.vue";

import { reactive, ref, onBeforeMount } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute } from "vue-router";
import type { FormRules, FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { Delete } from "@element-plus/icons-vue";
import { useTabsStore } from "@/stores/modules/tabs";

const route = useRoute();
const { t } = useI18n();
const tabStore = useTabsStore();

const rules = reactive<FormRules>({
  is_unique: [{ required: true, message: t("common.field.rule.config"), trigger: "blur" }],
  config_id: [{ required: true, message: t("common.field.rule.config"), trigger: "blur" }],
  label: [{ required: true, message: t("common.field.rule.label"), trigger: "blur" }],
  field: [{ required: true, message: t("common.field.rule.field"), trigger: "blur" }],
  // value: [{ required: true, message: t("common.field.rule.value"), trigger: "blur" }],
  input_type: [{ required: true, message: t("common.field.rule.input"), trigger: "blur" }],
  input: [{ required: true, message: t("common.field.rule.input"), trigger: "blur" }]
});

const config_id = route.params.config_id > 0 ? route.params.config_id : 0;

const ruleForm = reactive({
  id: route.params.id > 0 ? route.params.id : 0,
  config_id: config_id,
  is_unique: 1,
  label: "",
  field: "",
  input: "input",
  value: "",
  source: [],
  props: [],
  rules: [
    {
      required: true,
      message: "必填"
    }
  ],
  desc: "",
  status: 10
});

const inputItems = reactive([
  "input",
  "radio",
  "select",
  "switch",
  "timePicker",
  "timeSelect",
  "datePicker",
  "dateTimePicker",
  "checkbox",
  "resources"
]);

const ruleFormRef = ref<FormInstance>();
const submitForm = async (formEl: FormInstance | undefined) => {
  console.log(formEl);

  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      const action = ruleForm.id > 0 ? Update : Create;
      const Form = JSON.parse(JSON.stringify(ruleForm));
      action(Form).then(response => {
        ElMessage.success(response.message);
        setTimeout(() => {
          if (route.meta.isAffix) return;
          tabStore.removeTabs(route.fullPath);
          keepAliveStore.removeKeepAliveName(route.name as string);
        }, 200);
      });
    } else {
      ElMessage.error("请根据提示输入信息！");
    }
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
onBeforeMount(() => {
  if (route.params.id > 0) {
    getDetail({ id: route.params.id }).then(response => {
      ruleForm.id = response.data.id;
      ruleForm.config_id = response.data.config_id;
      ruleForm.label = response.data.label;
      ruleForm.is_unique = response.data.is_unique;
      ruleForm.field = response.data.field;
      ruleForm.input = response.data.input;
      ruleForm.value = response.data.value;
      ruleForm.source = JSON.parse(response.data.source);
      ruleForm.rules = JSON.parse(response.data.rules);
      ruleForm.props = JSON.parse(response.data.props);
      ruleForm.desc = response.data.desc;
      ruleForm.status = response.data.status;
    });
  }
});
//添加规则
const addRuleFormRef = ref<FormInstance>();
const addRuleDrawer = ref(false);
const addRules = () => {
  addRuleDrawer.value = true;
};
const ruleItem = reactive({
  rule: "",
  value: "",
  message: ""
});
const addRule = reactive<FormRules>({
  rule: [{ required: true, message: t("common.field.rule.rule"), trigger: "blur" }],
  value: [{ required: true, message: t("common.field.rule.value"), trigger: "blur" }],
  message: [{ required: true, message: t("common.field.rule.message"), trigger: "blur" }]
});
const addRuleItem = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (!valid) return ElMessage.error("请根据提示输入信息！");
    const rule = {};
    rule[ruleItem.rule] = ruleItem.value;
    rule.message = ruleItem.message;
    ruleForm.rules.push(rule);
    closeRuleItem(formEl);
  });
};
const closeRuleItem = (formEl: FormInstance | undefined) => {
  addRuleDrawer.value = false;
  if (!formEl) return;
  formEl.resetFields();
};
const delRules = index => {
  ruleForm.rules.splice(index, 1);
};

//添加 配置值
const addSourceDrawer = ref(false);
const addSourceFormRef = ref<FormInstance>();
const addSource = () => {
  addSourceDrawer.value = true;
};
const sourceItem = reactive({
  label: "",
  value: ""
});
const sourceRule = reactive<FormRules>({
  label: [{ required: true, message: t("common.field.rule.label"), trigger: "blur" }],
  value: [{ required: true, message: t("common.field.rule.value"), trigger: "blur" }]
});
const addSourceItem = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (!valid) return;
    const source = {};
    source.label = sourceItem.label;
    source.value = sourceItem.value;
    ruleForm.source.push(source);

    closeSourceItem(formEl);
  });
};
const closeSourceItem = (formEl: FormInstance | undefined) => {
  addSourceDrawer.value = false;
  if (!formEl) return;
  formEl.resetFields();
};
const delSource = index => {
  ruleForm.source.splice(index, 1);
};

//添加 prop
const addPropDrawer = ref(false);
const addPropFormRef = ref<FormInstance>();
const addProps = () => {
  addPropDrawer.value = true;
};
const propItem = reactive({
  label: "",
  value: ""
});
const propRule = reactive<FormRules>({
  label: [{ required: true, message: t("common.field.rule.attribute"), trigger: "blur" }],
  value: [{ required: true, message: t("common.field.rule.value"), trigger: "blur" }]
});
const addPropItem = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (!valid) return;
    const prop = {};
    prop[propItem.label] = propItem.value;
    ruleForm.props.push(prop);
    closePropItem(formEl);
  });
};
const closePropItem = (formEl: FormInstance | undefined) => {
  addPropDrawer.value = false;
  if (!formEl) return;
  formEl.resetFields();
};
const delProps = index => {
  ruleForm.props.splice(index, 1);
};
</script>

<style scoped lang="scss">
@import "./edit.scss";
</style>
